package P150;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LiangMu
 * @version \$Id: P30.java, v 0.1, 2024年07月05日 21:02 LiangMu Exp $$
 */
public class P30 {

    public static List<Integer> findSubstring(String s, String[] words) {
        int length = words[0].length();
        int sumLen = length * words.length;
        if (sumLen > s.length()) {
            return Collections.emptyList();
        }
        Arrays.sort(words);
        Set<String> set = Arrays.stream(words).map(it -> it.substring(0, 1)).collect(Collectors.toSet());
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i <= s.length() - sumLen; ++i) {
            if (set.contains(String.valueOf(s.charAt(i)))) {
                String substring = s.substring(i, i + sumLen);
                String[] target = spiltByLength(substring, words.length, length);
                boolean match = isMatch(target, words);
                if (match) {
                    result.add(i);
                }
            }
        }
        return result;
    }

    private static boolean isMatch(String[] str1, String[] str2) {
        Arrays.sort(str1);
        for (int i = 0; i < str1.length; i++) {
            if (!str1[i].equals(str2[i])) {
                return false;
            }
        }
        return true;
    }

    private static String[] spiltByLength(String s, int arrLen, int len) {
        String[] result = new String[arrLen];
        int index = 0;
        for (int i = 0; i < s.length(); i += len) {
            String substring = s.substring(i, i + len);
            result[index++] = substring;
        }
        return result;
    }

    public static void main(String[] args) {
        String s = "wordgoodgoodgoodbestword";
        String[] strs = {"word","good","best","good"};
        System.out.println(findSubstring(s, strs));
    }
}
